<template>
    <a-modal :confirm-loading="modalOption.loading" :okText="modalOption.okText" @ok="modalOption.onOk"
             @cancel="modalOption.onCancel" :cancelText="modalOption.cancelText" :width="modalOption.width" :visible="visible"
             :title="modalOption.title">
        <a-spin tip="loading" :spinning="loading">
            <div class="container">
                <a-form-model ref="formModel" :label-col="formOption.labelCol" :wrapper-col="formOption.wrapperCol"
                              :layout="formOption.layout" :label-align="formOption.labelAlign" :hide-required-mark="formOption.hideRequiredMark"
                              :rules="formOption.rules" :model="formOption.formData">
                    <!-- 检验信息 -->
                    <a-card title="检验信息" hoverable>
                        <div v-for="(item, idx) in formOption.formData.inspections" :key="idx" style="margin-bottom: 8px;">
                            <a-row :gutter="16" type="flex">
                                <a-col :span="4">
                                    <a-form-model-item label="质量状态:" :prop="`inspections[${idx}].qualityState`">
                                        <a-select :disabled="item.disabled" v-model="item.qualityState" placeholder="质量状态" @change="qualityStateChange(idx)">
                                            <a-select-option value="合格">合格</a-select-option>
                                            <a-select-option value="不合格">不合格</a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="4">
                                    <a-form-model-item label="报告日期:" :prop="`inspections[${idx}].reportTime`">
                                        <a-date-picker :disabled="item.disabled" v-model="item.reportTime" valueFormat="YYYY-MM-DD" placeholder="报告日期" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="4">
                                    <a-form-model-item label="取样量:" :prop="`inspections[${idx}].amount`">
                                        <a-input :disabled="item.disabled" v-model="item.amount" placeholder="取样量" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="4">
                                    <a-form-model-item :label="tabName==='制粒库存表'?'复验期(月):':'有效期(月):'" :prop="`inspections[${idx}].validity`">
                                        <a-input disabled v-model="item.validity" :placeholder="tabName==='制粒库存表'?'复验期(月)':'有效期(月)'" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="4" v-if="item.qualityState==='合格'">
                                    <a-form-model-item :label="tabName==='总混一库存表'?'有效期至:':'复检日期:'" :prop="`inspections[${idx}].recheckTime`">
                                        <a-date-picker disabled v-model="item.recheckTime" valueFormat="YYYY-MM-DD" :placeholder="tabName==='总混一库存表'?'有效期至':'复检日期'" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="4" style="display: flex; align-items: flex-start;flex-direction: row-reverse;">
                                    <a-button style="height: 38px;" type="danger" icon="minus" @click="removeInspection(item.id)" :disabled="formOption.formData.inspections.length <= 1">删除</a-button>
                                    <a-button style="height: 38px;" v-if="idx === formOption.formData.inspections.length - 1" type="primary" icon="plus" @click="addInspection" :disabled="formOption.formData.inspections.length >= 5">添加</a-button>
                                </a-col>
                            </a-row>
                        </div>
                    </a-card>
                </a-form-model>
            </div>
            <div slot="footer" style="text-align: center">
                <a-button size="large" @click="modalOption.onCancel">取 消</a-button>
                <a-button size="large" type="primary" @click="modalOption.onOk">确 定</a-button>
            </div>
        </a-spin>
    </a-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import locale from "ant-design-vue/lib/date-picker/locale/zh_CN";
import nextApi from "@/api/nextApi";

interface FormData {
    inspections: Array<{
        qualityState: string;
        reportTime: string;
        amount: string;
        validity: string;
        recheckTime: string;
    }>;
    [key: string]: any;
}

@Component({})
export default class extends Vue {
    @Prop({default:''}) tabName!:string;
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: "" }) editId!: string;
    @Prop({ default: () => ({}) }) formData!: FormData;

    @Watch("visible")
    visibleChange(val) {
        if (val) {
            this.getInfoByBatchAndType()
            this.formOption.rules = {
                    'inspections[0].qualityState': [
                        { required: true, message: '请选择质量状态', trigger: 'change' }
                    ],
                    // 'inspections[0].reportTime': [
                    //     { required: true, message: '请选择报告日期', trigger: 'change' }
                    // ],
                    'inspections[0].amount': [
                        { required: true, message: '请输入取样量', trigger: 'blur' },
                        { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式', trigger: 'blur' }
                    ],
                    'inspections[0].validity': [
                        { required: true, message: '请输入有效期', trigger: 'blur' },
                        { pattern: /^\d+$/, message: '请输入整数', trigger: 'blur' }
                    ],
                    'inspections[0].recheckTime': [
                        { required: true, message: '请选择复检日期', trigger: 'change' }
                    ]
                }
        } else {
            (this.$refs.formModel as any).resetFields();
            this.formOption.formData = {};
        }
    }

    loading = false;
    validityMonth = 0
    type = ''
    batch = ''

    //组件配置
    modalOption: any = {
        locale: locale,
        width: "95%",
        title: "质量检验",
        okText: "保存",
        cancelText: "取消",
        loading: false,
        onOk: () => {
            this.modalOk();
        },
        onCancel: () => {
            this.closeModal();
        },
    };

    //表单配置
    formOption: any = {
        labelCol: { style: { width: "90px" } },
        wrapperCol: { style: {width:'calc(100% - 90px)'}},
        layout: "inline",
        labelAlign: "right",
        hideRequiredMark: false,
        formData: {},
        rules: {},
    };

    async getInfoByBatchAndType(){
        let params = {
            nonProdId:this.editId
        }
        const res = await nextApi.getCheckInfo(params)
        
        if(res.data.length){
            // 使用Vue.set或this.$set来确保响应式更新
            let checkInfo = res.data
            checkInfo.forEach(item=>{
                item.disabled = true
            })
            this.validityMonth = checkInfo[0].validity
            this.$set(this.formOption.formData, 'inspections', [...checkInfo])
        }else{
            this.initList()
        }
        
    }
    async initList(){
        if(this.tabName ==='饮片库存表'){
            this.validityMonth = this.formData.ypValidity
        }else if(this.tabName === '收粉库存表'){
            this.validityMonth = this.formData.sfValidity
        }else if(this.tabName === '过筛库存表'){
            this.validityMonth = this.formData.gsValidity
        }else if(this.tabName === '总混一库存表'){
            this.validityMonth = this.formData.zhyValidity
        }else if(this.tabName === '总混二库存表'){
            this.validityMonth = this.formData.zheValidity
        }else{
            //根据zlId查询产品数据
            let params = {
                id:this.formData.zlId,
            }
            const res = await nextApi.selectDetailById(params)
            if(res?.data){
                this.validityMonth = res.data.reInspection
            }else{
                this.validityMonth = 0
            }
        }
        this.type = this.tabName.length === 5 ? this.tabName.substring(0,2):this.tabName.substring(0,3)
        
        // 使用Vue.set或this.$set来确保响应式更新
        this.$set(this.formOption, 'formData', {
            inspections: [
                { qualityState: '',nonProdId:this.editId, type:this.type ,batch: this.batch, reportTime: '', amount: '', validity: this.validityMonth, recheckTime: '' }
            ]
        });
    }
    async qualityStateChange(idx){
        const item = this.formOption.formData.inspections[idx];
        let inDate:any
        if(this.tabName == "收粉库存表"){
            inDate = new Date(this.formData.sfInTime);
            const recheckTime = new Date(inDate)
            recheckTime.setMonth(inDate.getMonth()*1 + this.validityMonth*1)
            item.recheckTime = recheckTime.toISOString().split('T')[0];
        }else if(this.tabName === "过筛库存表"){
            inDate = new Date(this.formData.gsInTime);
            const recheckTime = new Date(inDate)
            recheckTime.setMonth(inDate.getMonth()*1 + this.validityMonth*1)
            item.recheckTime = recheckTime.toISOString().split('T')[0];
        }else if(this.tabName === "总混二库存表"){
            inDate = new Date(this.formData.zheInTime);
            const recheckTime = new Date(inDate)
            recheckTime.setMonth(inDate.getMonth()*1 + this.validityMonth*1)
            item.recheckTime = recheckTime.toISOString().split('T')[0];
        }else if(this.tabName === "饮片库存表"){
            inDate = new Date(this.formData.ypInTime);
            const recheckTime = new Date(inDate)
            recheckTime.setMonth(inDate.getMonth()*1 + this.validityMonth*1)
            item.recheckTime = recheckTime.toISOString().split('T')[0];
        }
        this.reportTimeChange(idx)
    }
    async reportTimeChange(idx) {
        const item = this.formOption.formData.inspections[idx];
        if (item.qualityState === '合格' && item.validity) {
            if(this.tabName==='制粒库存表'){
                if(!this.formData.zlTime){
                    this.$message.error('请填写生产日期')
                    return
                }
                const reportTime = new Date(this.formData.zlTime);
                // 将有效期转换为月数
                const validityMonths = parseInt(item.validity);
                // 计算复检日期
                const recheckTime = new Date(reportTime);
                recheckTime.setMonth(reportTime.getMonth() + validityMonths);
                // 格式化日期为YYYY-MM-DD
                item.recheckTime = recheckTime.toISOString().split('T')[0];
            }
             if(this.tabName==='总混一库存表'){
                if(!this.formData.zhyInTime){
                    this.$message.error('请填写入库日期')
                    return
                }
                const reportTime = new Date(this.formData.zhyInTime);
                // 将有效期转换为月数
                const validityMonths = parseInt(item.validity);
                // 计算复检日期
                const recheckTime = new Date(reportTime);
                recheckTime.setMonth(reportTime.getMonth() + validityMonths);
                // 格式化日期为YYYY-MM-DD
                item.recheckTime = recheckTime.toISOString().split('T')[0];
                //将计算后的时间日期减去一天
                const adjustedDate = new Date(item.recheckTime);
                adjustedDate.setDate(adjustedDate.getDate() - 1);
                item.recheckTime = adjustedDate.toISOString().split('T')[0]; 
            }
            
            
            
        }
    }

    //提交
    modalOk() {
        (this.$refs.formModel as any).validate(async (valid: boolean) => {
            if (valid) {
                this.modalOption.loading = true;
                try {
                    const params = this.formOption.formData.inspections
                    console.log(params);
                    const res = await nextApi.addCheckInfo(params);
                    this.$message.success(res.msg);
                    this.$emit("closeModal");
                } finally {
                    this.modalOption.loading = false;
                }
            }
        });
    }

    closeModal() {
        this.$emit("closeModal");
    }

    // 检验信息操作
    addInspection() {
        if (this.formOption.formData.inspections.length < 5) {
            this.type = this.tabName.length === 5 ? this.tabName.substring(0,2):this.tabName.substring(0,3)
            this.formOption.formData.inspections.push({
                qualityState: '',
                reportTime: '',
                amount: '',
                validity:this.validityMonth,
                recheckTime: '',
                type:this.type,
                batch:this.batch,
                nonProdId:this.editId,
            });
        }
    }

    async removeInspection(id) {
        const res = await nextApi.removeCheckInfoById({id})
        this.$message.success(res.msg)
        this.getInfoByBatchAndType()
    }   
}
</script>

<style scoped lang="scss">
.container {
    padding: 0;
    .ant-input,
    .ant-select,
    .ant-calendar-picker,
    .ant-picker {
        width: 200px !important;
        min-width: 120px;
        height: 32px;
        line-height: 32px;
    }
    .ant-form-item {
        margin-bottom: 16px;
    }
    .ant-card {
        margin-bottom: 16px;
    }
    .ant-form-item-label > label {
        height: 32px;
        line-height: 32px;
        font-size: 14px;
    }
    .ant-btn {
        height: 32px;
        line-height: 32px;
        min-width: 60px;
        padding: 0 16px;
        margin-right: 4px;
    }
}
</style>